package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// 产品表
type Product struct {
	ID            string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	Name          string    `json:"name" gorm:"type:varchar(100);not null"`
	PublicID      string    `json:"public_id" gorm:"type:varchar(100);uniqueIndex;not null"`
	SignType      string    `json:"sign_type" gorm:"type:varchar(20);default:'HMAC_SHA512'"` // ECC/RSA/HMAC_SHA512
	SignKey       string    `json:"sign_key" gorm:"type:varchar(1024)"`                      // 签名密钥
	LatestVersion string    `json:"latest_version" gorm:"type:varchar(50)"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

// 固件版本表
type Firmware struct {
	ID          string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	Version     string    `json:"version" gorm:"type:varchar(50);not null"`
	Signature   string    `json:"signature" gorm:"type:text"`
	ReleaseTime time.Time `json:"release_time"`
	ProductID   string    `json:"product_id" gorm:"type:varchar(36);not null"`
	Description string    `json:"description" gorm:"type:text"`
	DownloadURL string    `json:"download_url" gorm:"type:varchar(500)"`
	FileSize    int64     `json:"file_size"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`

	Product Product `json:"product" gorm:"foreignKey:ProductID"`
}

// 任务表
type Task struct {
	ID            string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	Name          string    `json:"name" gorm:"type:varchar(100);not null"`
	EffectiveTime time.Time `json:"effective_time"`
	TaskType      string    `json:"task_type" gorm:"type:varchar(50);not null"` // 升级任务类型
	SN            string    `json:"sn" gorm:"type:varchar(100)"`                // 设备序列号，为空表示所有设备
	ProductID     string    `json:"product_id" gorm:"type:varchar(36);not null"`
	Version       string    `json:"version" gorm:"type:varchar(50);not null"`
	TenantID      string    `json:"tenant_id" gorm:"type:varchar(36)"`
	ExecuteTime   string    `json:"execute_time" gorm:"type:varchar(20)"`             // 执行时间段，如 "02:00-04:00"
	Status        string    `json:"status" gorm:"type:varchar(20);default:'pending'"` // pending, running, completed, failed
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`

	Product Product `json:"product" gorm:"foreignKey:ProductID"`
}

// 升级记录表
type UpgradeRecord struct {
	ID          string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	SN          string    `json:"sn" gorm:"type:varchar(100);not null;index"`
	ProductID   string    `json:"product_id" gorm:"type:varchar(36);not null"`
	Version     string    `json:"version" gorm:"type:varchar(50);not null"`
	UpgradeTime time.Time `json:"upgrade_time"`
	Status      string    `json:"status" gorm:"type:varchar(20);not null"` // success, failed, in_progress
	Message     string    `json:"message" gorm:"type:text"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`

	Product Product `json:"product" gorm:"foreignKey:ProductID"`
}

// 终端列表
type Device struct {
	ID             string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	SN             string    `json:"sn" gorm:"type:varchar(100);not null"`
	ProductID      string    `json:"product_id" gorm:"type:varchar(36);not null"`
	CurrentVersion string    `json:"current_version" gorm:"type:varchar(50)"`
	LastCheckTime  time.Time `json:"last_check_time"`
	Status         string    `json:"status" gorm:"type:varchar(20);default:'online'"` // online, offline
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`

	Product Product `json:"product" gorm:"foreignKey:ProductID"`
}

// 登录失败记录表
type LoginFailure struct {
	ID        string    `json:"id" gorm:"primaryKey;type:varchar(36)"`
	IP        string    `json:"ip" gorm:"type:varchar(45);not null;index"` // 支持IPv6
	Username  string    `json:"username" gorm:"type:varchar(100);not null"`
	Timestamp time.Time `json:"timestamp" gorm:"not null;index"`
	UserAgent string    `json:"user_agent" gorm:"type:varchar(500)"` // 浏览器信息
	CreatedAt time.Time `json:"created_at"`
}

// IP黑名单表
type IPBlacklist struct {
	ID           string     `json:"id" gorm:"primaryKey;type:varchar(36)"`
	IP           string     `json:"ip" gorm:"type:varchar(45);uniqueIndex;not null"`
	BlockedAt    time.Time  `json:"blocked_at" gorm:"not null"`
	UnblockedAt  *time.Time `json:"unblocked_at"`                    // null表示永久封禁
	Reason       string     `json:"reason" gorm:"type:varchar(200)"` // 封禁原因
	FailureCount int        `json:"failure_count" gorm:"default:0"`  // 失败次数
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
}

// BeforeCreate 钩子，自动生成UUID
func (p *Product) BeforeCreate(tx *gorm.DB) error {
	if p.ID == "" {
		p.ID = uuid.New().String()
	}
	return nil
}

func (f *Firmware) BeforeCreate(tx *gorm.DB) error {
	if f.ID == "" {
		f.ID = uuid.New().String()
	}
	return nil
}

func (t *Task) BeforeCreate(tx *gorm.DB) error {
	if t.ID == "" {
		t.ID = uuid.New().String()
	}
	return nil
}

func (u *UpgradeRecord) BeforeCreate(tx *gorm.DB) error {
	if u.ID == "" {
		u.ID = uuid.New().String()
	}
	return nil
}

func (d *Device) BeforeCreate(tx *gorm.DB) error {
	if d.ID == "" {
		d.ID = uuid.New().String()
	}
	return nil
}

func (lf *LoginFailure) BeforeCreate(tx *gorm.DB) error {
	if lf.ID == "" {
		lf.ID = uuid.New().String()
	}
	return nil
}

func (ib *IPBlacklist) BeforeCreate(tx *gorm.DB) error {
	if ib.ID == "" {
		ib.ID = uuid.New().String()
	}
	return nil
}
